# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import scrapy

from entity.Article import Article
from scrapy.exceptions import DropItem

from utils.PageUtil import PageUtil
from utils.Constants import logging

class Pipeline(object):

    def __init__(self):
        self.logger = logging.getLogger(self.__class__.__name__)

    def open_spider(self,spider):
        pass

    def process_item(self,item,spider):
        pass

    def close_spider(self,spider):
        pass


class Validator(Pipeline):
    """
    验证爬取的文章对象是否合法,是否完整
    """

    def __init__(self):
        super(Validator,self).__init__()

    def process_item(self, item, spider):
        validate = not (item.get('url')==None or
                    item.get('title') == None or
                    item.get('content') == None or
                    len(item.get('content')) < 10)
        if not validate:
            self.logger.warning("InValidate Response For "+spider.name + "  On URL = "+item['url'])
            raise DropItem("Illegal Article Item!")
        else:
            return item

class FilePersistant(Pipeline):
    """
    以json文件的形式存储页面
    """
    def process_item(self, item, spider):
        PageUtil.save(Article().fromItem(item))
        return item


class DBPersistant(Pipeline):
    pass